package org.bigmarketapi.projectreview.concurrent;

/**
 * @BelongsProject: ProjectReview
 * @BelongsPackage: org.bigmarketapi.projectreview.concurrent
 * @Author: dujiaqi
 * @CreateTime: 2024-08-14  11:02
 * @Description: TODO
 * @Version: 1.0
 */
public class PrintInSequence {

    private static final Object lock = new Object();
    private static int currentThread = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> printChar('A', "Thread A"));
        Thread t2 = new Thread(() -> printChar('B', "Thread B"));
        Thread t3 = new Thread(() -> printChar('C', "Thread C"));

        t1.start();
        t2.start();
        t3.start();
    }

    private static void printChar(char c, String name) {
        for (int i = 0; i < 10; i++) {
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName());
                while (currentThread != (c - 'A' + 1)) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;

                    }
                }
                System.out.println(c);
                // 切换到下一个线程
                currentThread = (currentThread % 3) + 1;
                lock.notifyAll();
            }
        }
    }
}
